package com.kischang.blog.dao;

import com.kischang.blog.model.BrowseHistory;
import com.kischang.blog.model.PageInfo;
import com.kischang.blog.model.Topic;
import com.kischang.blog.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TopicDao {
	@Autowired
	private SessionFactory sessionFactory;
    @Autowired
    private UserDao userDao;

	@SuppressWarnings("unchecked")
	public List<Topic> getTopicByPage(PageInfo pageInfo){
		Session session = sessionFactory.getCurrentSession();
		return session.createQuery("FROM Topic AS t WHERE t.state=0 ORDER BY t.id DESC")
				.setFirstResult((pageInfo.getPageNow()-1)*pageInfo.getPageSize())
				.setMaxResults(pageInfo.getPageSize())
				.list();
	}
	public int getTopicCount(){
		Session session = sessionFactory.getCurrentSession();
		return ((Long) session.createQuery("SELECT COUNT(t.id) FROM Topic AS t WHERE t.state=0")
				.uniqueResult()).intValue();
	}
	@SuppressWarnings("unchecked")
	public List<Topic> getTopicByPageAndMenu(int mid,PageInfo pageInfo){
		Session session = sessionFactory.getCurrentSession();
		return session.createQuery("FROM Topic AS t WHERE t.titleColumn=:mid AND t.state=0 ORDER BY t.id DESC")
				.setInteger("mid",mid)
				.setFirstResult((pageInfo.getPageNow()-1)*pageInfo.getPageSize())
				.setMaxResults(pageInfo.getPageSize())
				.list();
	}
	public int getTopicCountByMenu(int mid){
		Session session = sessionFactory.getCurrentSession();
		return ((Long) session.createQuery("SELECT COUNT(t.id) FROM Topic AS t WHERE t.titleColumn=:mid AND t.state=0")
				.setInteger("mid",mid)
				.uniqueResult()).intValue();
	}
	public Topic getTopicByID(int tid, boolean add, User user) {
		Session session = sessionFactory.getCurrentSession();
        Topic topic =  (Topic) session.createQuery("FROM Topic AS t WHERE t.id=:tid AND t.state=0")
				.setInteger("tid",tid)
				.uniqueResult();
        if(add){
            if (topic.getPv() <= 0 ){
                topic.setPv(1);
            }else{
                topic.setPv(topic.getPv() + 1);
            }
            session.update(topic);
            if(user != null){
                user = userDao.findUserByUsername(user.getUsername());
                session.save(new BrowseHistory(user,topic));
            }
        }
        return topic;
	}
	public void save(Topic topic) {
		sessionFactory.getCurrentSession().save(topic);
	}
	public void update(Topic topic) {
		sessionFactory.getCurrentSession().update(topic);
	}
}
